package com.zgjkhis.modules.util;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;

/**
 * http请求工具类
 * @ClassName:  ConnectionUrlUtil
 * @author: yxl
 * @date:   2019年2月12日 下午4:05:50
 * @version V2.0
 */
@Slf4j
public class ConnectionUrlUtil {

	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数
	 * @return 返回结果
	 */
	public static String sendPostOut(String url, String parameter,int timeOut) {
		log.info("sendPostOut请求地址:" + url);
		log.info("sendPostOut请求参数:" + parameter);
		log.info("sendPostOut时间:" + timeOut);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(timeOut);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));
			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendPostOut请求结果:" + result);
		} catch (Exception ex) {
			log.error("sendPostOut请求异常", ex);
		}
		return result;
	}


	/**
	 * 设置响应时间
	 */
	public static String sendGetOut(String url, String param,int timeOut) {
		log.info("sendGetOut请求地址:" + url);
		log.info("sendGetOut请求参数:" + param);
		log.info("sendGetOut请求时间:" + timeOut);
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setConnectTimeout(timeOut);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            result = new String(result.getBytes(), StandardCharsets.UTF_8);
            log.info("sendGetOut请求结果:" + result);
        } catch (Exception e) {
            log.error("sendGetOut请求异常", e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("sendGetOut请求关闭异常", e2);
            }
        }
        return result;
    }

	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数
	 * @return 返回结果
	 */
	public static String sendJsonPostByPut(String url, String parameter,String token) {
		log.info("sendJsonPost请求地址:" + url);
		log.info("sendJsonPost请求参数:" + parameter);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("PUT");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			conn.setRequestProperty("Authorization", "bearer "+token);
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(60000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendJsonPost请求结果:" + result);
		} catch (Exception ex) {
			log.error("sendJsonPost请求异常", ex);
		}
		return result;
	}




	public static String sendJsonPostNoLog(String url, String parameter) {
		log.info("sendJsonPost请求地址:" + url);
		log.info("sendJsonPost请求参数:" + parameter);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(60000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendJsonPost请求结果长度:" + result.length());
		} catch (Exception ex) {
			log.error("sendJsonPost请求异常", ex);
		}
		return result;
	}

	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数second超时时间
	 * @return 返回结果
	 */
	public static String sendJsonSecondPost(String url, String parameter,int second) {
		log.info("sendJsonSecondPost请求地址:" + url);
		log.info("sendJsonSecondPost请求参数:" + parameter);
		log.info("sendJsonSecondPost请求时间:" + second);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(second);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(second);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendJsonSecondPost请求结果:" + result);
		} catch (Exception ex) {
			log.error("sendJsonSecondPost请求异常", ex);
		}
		return result;
	}



	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数
	 * @return 返回结果
	 */
	public static String sendPost(String url, String parameter) {
		log.info("sendPost请求地址:" + url);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(20000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(20000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendPost请求结果:" + result);
		} catch (Exception ex) {
			log.error("sendPost请求异常", ex);
		}
		return result;
	}

	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数
	 * @return 返回结果
	 */
	public static String sendPostForToken(String url, String parameter) {
		log.info("sendPost请求地址:" + url);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(20000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(20000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendPost请求结果:" + result);
		} catch (Exception ex) {
			log.error("sendPost请求异常", ex);
		}
		return result;
	}

	/**
	 * 上传图片
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @param contentType 没有传入文件类型默认采用application/octet-stream
	 * contentType非空采用filename匹配默认的图片类型
	 * @return 返回response数据
	 */
	@SuppressWarnings("rawtypes")
	public static String formUpload(String urlStr, Map<String, String> textMap,
									Map<String, String> fileMap, String contentType, String token) {
		String res = "";
		HttpURLConnection conn = null;
		// boundary就是request头和上传文件内容的分隔符
		String boundary = "---------------------------123821742118716";
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Authorization", "bearer "+token);//zh-CN代表中国  默认为美式英语
			conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}
			// file
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					String filename = inputName;
					if(filename.indexOf(".")<=0){
						filename=filename+".jpg";
					}

//					//没有传入文件类型，同时根据文件获取不到类型，默认采用application/octet-stream
					contentType = new MimetypesFileTypeMap().getContentType(filename);
//					//contentType非空采用filename匹配默认的图片类型
					if(!"".equals(contentType)){
						if (filename.endsWith(".png")) {
							contentType = "image/png";
						}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
							contentType = "image/jpeg";
						}else if (filename.endsWith(".gif")) {
							contentType = "image/gif";
						}else if (filename.endsWith(".ico")) {
							contentType = "image/image/x-icon";
						}
					}
					if (contentType == null || "".equals(contentType)) {
						contentType = "application/octet-stream";
					}
					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"files\"; filename=\"" + filename + "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
					out.write(strBuf.toString().getBytes());
					out.write(getFile(inputValue));
				}
			}
			byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();
			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}

	/**
	 * 获取 文件 流
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static byte[] getFile(String url) throws IOException{
		InputStream inStream=null;
		try{
			URL urlConet = new URL(url);
			HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
			con.setRequestMethod("GET");
			con.setConnectTimeout(4 * 1000);
			 inStream = con .getInputStream();    //通过输入流获取图片数据
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[2048];
			int len = 0;
			while( (len=inStream.read(buffer)) != -1 ){
				outStream.write(buffer, 0, len);
			}
			inStream.close();
			byte[] data =  outStream.toByteArray();
			return data;
		}catch (Exception e){
			log.info("读取图片流错误：",e);
			return null;
		}finally {
			if(inStream!=null){
				inStream.close();
			}
		}
	}

	/**
	 * get的请求
	 */
	public static String sendGet(String url, String param) {
		log.info("sendGet请求地址:" + url);
		log.info("sendGet请求参数:" + param);
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            result = new String(result.getBytes(), StandardCharsets.UTF_8);
            log.info("sendGet请求结果:" + result);
        } catch (Exception e) {
            log.error("sendGet请求异常", e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("sendGet请求关闭异常", e2);
            }
        }
        return result;
    }


	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数
	 * @return 返回结果
	 */
	public static byte[] sendJsonPostForQrCode(String url, String parameter) {
		log.info("sendJsonPost请求地址:" + url);
		log.info("sendJsonPost请求参数:" + parameter);
		String result = "";
		InputStream in=null;
		ByteArrayOutputStream output=null;
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(60000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			 in = conn.getInputStream();
			 output = new ByteArrayOutputStream();
	        byte[] buffer = new byte[4096];
	        int n = 0;
	        while (-1 != (n = in.read(buffer))) {
	            output.write(buffer, 0, n);
	        }

			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			return output.toByteArray();
		} catch (Exception ex) {
			log.error("sendJsonPost请求异常", ex);
		} // 使用finally块来关闭输入流
        finally {
            try {
            	 if (output != null) {
                 	output.close();
                 }
                if (in != null) {
                    in.close();
                }

            } catch (Exception e2) {
                log.error("sendJsonPost请求关闭异常", e2);
            }
        }
		return null;
	}


	/**
	 * 发送post请求
	 * @param url  路径
	 * @param jsonObject  参数(json类型)
	 * @return
	 * @throws IOException
	 */
	public static String send(String url, JSONObject jsonObject){
		try{
			String body = "";
			//创建httpclient对象
			CloseableHttpClient client = HttpClients.createDefault();
			//创建post方式请求对象
			HttpPost httpPost = new HttpPost(url);

			//装填参数
			StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			//设置参数到请求对象中
			httpPost.setEntity(s);
			System.out.println("请求地址："+url);
//        System.out.println("请求参数："+nvps.toString());

			//设置header信息
			httpPost.setHeader("Content-type", "application/json");
			httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

			//执行请求操作，并拿到结果（同步阻塞）
			CloseableHttpResponse response = client.execute(httpPost);
			//获取结果实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "utf-8");
			}
			EntityUtils.consume(entity);
			//释放链接
			response.close();
			return body;
		}catch (Exception e){
			log.error("发送请求错误：",e);
		}
		return null;
	}

	/**
	 * post提交
	 * @param url 接收的url
	 * @param parameter 接收的参数
	 * @return 返回结果
	 */
	public static String sendJsonPost(String url, String parameter) {
		log.info("sendJsonPost请求地址:" + url);
		log.info("sendJsonPost请求参数:" + parameter);
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte[] contentbyte = parameter.getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
//			conn.setRequestProperty("Authorization", "bearer ");
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(60000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2
			// http正文内，因此需要设为true, 默认情况下是false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bWriter.write(parameter);
			bWriter.flush();
			bWriter.close();
			// 调用HttpURLConnection连接对象的getInputStream()函数,
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1) {
					buffer.append((char) i);
				}
			}
			in.close();
			//此方法是用Reader读取BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream()));

			result = new String(buffer.toString().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			log.info("sendJsonPost请求结果:" + result);
		} catch (Exception ex) {
			log.error("sendJsonPost请求异常", ex);
		}
		return result;
	}

}
